<template>
  <div class="voice">
    <x-header :left-options="{backText: ''}">党员心声</x-header>
    <div class="voice_content">
      <group title="标题">
        <x-input v-model="helpObject" placeholder="请输入标题"></x-input>
      </group>

      <group title="内容">
        <x-textarea placeholder="这一刻的想法..." v-model="helpMessage"></x-textarea>
        <div class="weui-cells_form" id="uploaderCustom">
          <div class="weui-cell">
            <div class="weui-cell__bd">
              <div class="weui-uploader">
                <div class="weui-uploader__bd">
                  <ul class="weui-uploader__files" id="uploaderCustomFiles"></ul>
                  <div class="weui-uploader__input-box">
                    <input id="uploaderCustomInput" name="image[]" class="weui-uploader__input js_file"
                    type="file" accept="image/*">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </group>
      <x-button type="primary" :show-loading="showLoading" :disabled="!isClicked" @click.native="submit">发布</x-button>
      <router-link to="recording/recording" class="record">发布记录</router-link>
    </div>


  </div>
</template>

<script>
import { XHeader, Group, XInput, XTextarea, XButton } from "vux";
import api from "../../api/index";
import axios from "axios";
export default {
  components: {
    XHeader,
    Group,
    XInput,
    XTextarea,
    XButton
  },
  activated() {
    this.helpObject = "";
    this.helpMessage = "";

    this.filesArr = [];

    this.showLoading = false;
    this.isClicked = false;

    this.$el.querySelector("#uploaderCustomFiles").innerHTML = "";
  },
  data() {
    return {
      helpObject: "",
      helpMessage: "",
      showLoading: false,
      isClicked: false,
      maxSize: 10240000,
      maxCount: 9,
      filesArr: [],
      hasImg: 0
    };
  },
  mounted() {
    this.bindEvent();
    this.delImg();
  },
  watch: {
    helpObject: function(value) {
      if (value && this.helpMessage) {
        this.isClicked = true;
      }
    },
    helpMessage: function(value) {
      if (value && this.helpObject) {
        this.isClicked = true;
      }
    },
    filesArr: function(value) {
      if (value.length >= this.maxCount) {
        let uploader = document.querySelector(".weui-uploader__input-box");
        uploader.style.display = "none";
      } else {
        let uploader = document.querySelector(".weui-uploader__input-box");
        uploader.style.display = "block";
      }
    }
  },
  methods: {
    bindEvent() {
      let self = this;
      let uploader = self.$el.querySelector("#uploaderCustomInput");
      let uploaderCustomeFiles = self.$el.querySelector("#uploaderCustomFiles");

      uploader.addEventListener("change", function(event) {
        let files = event.target.files || event.dataTransfer.files;
        // 如果没有选中文件，直接返回
        if (files.length === 0) {
          return;
        }
        if (files.length >= self.maxCount) {
          self.$vux.toast.text(`最多上传${self.maxCount}张`, "middle");
          return;
        }

        for (var i = 0; i < files.length; i++) {
          let file = files[i];

          if (file.size >= self.maxSize) {
            self.$vux.toast.text(`最大不能超过10M`, "middle");
            return;
          }

          self.hasImg++;

          // self.filesArr.push(file);

          let reader = new FileReader();
          reader.onprogress = function(e) {
            let uploader_per = self.$el.querySelector(
              `#prview${self.hasImg} .percent`
            );

            let percent = Math.round(e.loaded / e.total * 100);
            if (percent < 100) {
              uploader_per.style.width = percent + "%";
              uploader_per.textContent = percent + "%";
            }
          };
          reader.onloadstart = function() {
            var $previewLi = `<li class="weui_uploader_file weui_uploader_status" id="prview${
              self.hasImg
            }"><div class="progress"><div class="percent">0%</div></div></li>`;
            let previewLi = self.parseToDOM($previewLi)[0];

            uploaderCustomeFiles.appendChild(previewLi);
          };
          reader.onload = function(e) {
            let uploader_file = self.$el.querySelector(`#prview${self.hasImg}`);
            let uploader_per = self.$el.querySelector(
              `#prview${self.hasImg} .percent`
            );

            var src = e.target.result;
            let data;

            var img = new Image();
            img.src = src;
            img.onload = function() {
              if (src.length <= 100 * 1024) {
                data = src;
              } else {
                data = self.compress(img);
              }

              uploader_file.setAttribute(
                "style",
                `background-image:url(${src})`
              );
              self.filesArr.push(self.dataURItoBlob(data));
            };

            uploader_per.style.width = "100%";
            uploader_per.textContent = "100%";

            let $delBtn = '<div class="weui_del"><i></i></div>';
            let delBtn = self.parseToDOM($delBtn)[0];

            uploader_file.innerHTML = $delBtn;
          };
          reader.readAsDataURL(file);
          uploader.value = "";
        }
      });
    },
    dataURItoBlob(dataUrl) {
      var byteString = atob(dataUrl.split(",")[1]);
      var mimeString = dataUrl
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    parseToDOM(str) {
      var ul = document.createElement("ul");
      if (typeof str == "string") ul.innerHTML = str;
      return ul.childNodes;
    },
    compress(img) {
      let canvas = document.createElement("canvas");
      // let ctx = canvas.getContext("2d");
      let context = canvas.getContext("2d");
      //瓦片canvas
      // let tCanvas = document.createElement("canvas");
      // let tctx = tCanvas.getContext("2d");
      var originWidth = img.width;
      var originHeight = img.height;
      let initSize = img.src.length;
      // 最大尺寸限制
      var maxWidth = 800,
        maxHeight = 800;
      // 目标尺寸
      var targetWidth = originWidth,
        targetHeight = originHeight;
      // 图片尺寸超过800x800的限制
      if (originWidth > maxWidth || originHeight > maxHeight) {
        if (originWidth / originHeight > maxWidth / maxHeight) {
          // 更宽，按照宽度限定尺寸
          targetWidth = maxWidth;
          targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        } else {
          targetHeight = maxHeight;
          targetWidth = Math.round(maxHeight * (originWidth / originHeight));
        }
      }
      // canvas对图片进行缩放
      canvas.width = targetWidth;
      canvas.height = targetHeight;
      // 清除画布
      context.clearRect(0, 0, targetWidth, targetHeight);
      // 图片压缩
      context.drawImage(img, 0, 0, targetWidth, targetHeight);
      // let width = img.width;
      // let height = img.height;
      //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      // let ratio;
      // if ((ratio = width * height / 4000000) > 1) {
      //   console.log("大于400万像素");
      //   ratio = Math.sqrt(ratio);
      //   width /= ratio;
      //   height /= ratio;
      // } else {
      //   ratio = 1;
      // }
      // canvas.width = width;
      // canvas.height = height;
      // //        铺底色
      // ctx.fillStyle = "#fff";
      // ctx.fillRect(0, 0, canvas.width, canvas.height);
      // //如果图片像素大于100万则使用瓦片绘制
      // let count;
      // if ((count = width * height / 1000000) > 1) {
      //   console.log("超过100W像素");
      //   count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
      //   //            计算每块瓦片的宽和高
      //   let nw = ~~(width / count);
      //   let nh = ~~(height / count);
      //   tCanvas.width = nw;
      //   tCanvas.height = nh;
      //   for (let i = 0; i < count; i++) {
      //     for (let j = 0; j < count; j++) {
      //       tctx.drawImage(
      //         img,
      //         i * nw * ratio,
      //         j * nh * ratio,
      //         nw * ratio,
      //         nh * ratio,
      //         0,
      //         0,
      //         nw,
      //         nh
      //       );
      //       ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
      //     }
      //   }
      // } else {
      //   ctx.drawImage(img, 0, 0, width, height);
      // }
      //修复ios上传图片的时候 被旋转的问题
      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.4);
      console.log("压缩前：" + initSize);
      console.log("压缩后：" + ndata.length);
      console.log(
        "压缩率：" + ~~(100 * (initSize - ndata.length) / initSize) + "%"
      );
      // tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
    delImg() {
      let self = this;
      let uploaderCustomeFiles = self.$el.querySelector("#uploaderCustomFiles");

      uploaderCustomeFiles.addEventListener("click", function(event) {
        let currentNode = event.target.parentNode.parentNode;

        let index = [...uploaderCustomeFiles.childNodes].indexOf(currentNode);
        self.filesArr.splice(index, 1);
        uploaderCustomeFiles.removeChild(
          uploaderCustomeFiles.childNodes[index]
        );
      });
    },
    submit() {
      const _this = this;

      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      _this.showLoading = true;
      let userid = window.localStorage.getItem("user");

      let uploadData = new FormData();
      _this.filesArr.map(file => {
        uploadData.append("image[]", file);
      });
      uploadData.append("author_id", userid);
      uploadData.append("title", this.helpObject);
      uploadData.append("content_feedback", this.helpMessage);

      let ax = axios.create();

      ax.post("/dyxs/problem/add", uploadData, config).then(res => {
        if (res.data.code === 1) {
          _this.showLoading = false;

          _this.$router.replace("/user");
        } else {
          this.$vux.toast.text(res.data.msg, "middle");
          _this.showLoading = false;
        }
      });
    }
  }
};
</script>

<style lang="less">
.voice {
  font-size: 0;
  min-height: 100vh;
  background: rgb(245, 245, 249);
  .voice_content {
    padding: 2.875rem 0 0;
  }
  .weui-cells__title {
    margin: 0.4375rem 0;
    padding: 0 10px;
    font-size: 0.875rem;
    color: rgb(102, 102, 102);
  }
  .weui-cells {
    font-size: 0.875rem;
    color: rgb(153, 153, 153);
    margin: 0;
  }
  .weui-cell__ft {
    text-align: left;
  }
  .vux-x-textarea {
    padding: 1.0625rem 1.8125rem 0.9375rem;
  }
  .weui-uploader__bd {
    margin-bottom: -4px;
    overflow: hidden;
  }
  .weui-cells_form .weui-cell {
    padding: 0 0 2.0625rem;
    text-align: center;
  }
  .weui-uploader {
    display: inline-block;
    width: 17.25rem;
  }
  .weui-uploader__input-box {
    float: left;
    position: relative;
    margin-bottom: 0.375rem;
    width: 5.5rem;
    height: 5.5rem;
    background: rgb(237, 236, 236);
  }

  .weui_uploader_file {
    float: left;
    margin-right: 0.375rem;
    margin-bottom: 0.375rem;
    width: 5.5rem;
    height: 5.5rem;
    background: #edecec center center;
    background-size: cover;
    list-style: none;
    overflow: hidden;
    position: relative;
    &:nth-child(3n) {
      margin-right: 0;
    }
    .weui_del {
      width: 100%;
      height: 20/16rem;
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0.3);
      i {
        display: inline-block;
        width: 20/16rem;
        height: 100%;
        background: url("./img/del.png") no-repeat;
        background-size: 100% 100%;
      }
    }
    .progress {
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.3);
      color: rgb(255, 255, 255);
      font-size: 13/16rem;
      .percent {
        background-color: #99ccff;
        height: auto;
        width: 0;
      }
    }
  }

  .weui-uploader__input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }

  .weui-uploader__input-box:before {
    width: 3px;
    height: 2.875rem;
  }

  .weui-uploader__input-box:after {
    width: 2.875rem;
    height: 3px;
  }

  .weui-uploader__input-box:after,
  .weui-uploader__input-box:before {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #fff;
  }
  .weui-btn {
    width: 21.25rem;
    margin-top: 36/16rem;
    background-color: rgb(214, 60, 50) !important;
    font-size: 1.125rem;
  }
  .weui-btn_disabled.weui-btn_primary {
    background: #d7d7d7 !important;
  }
  .record {
    width: 100%;
    padding: 1.8rem 0;
    display: inline-block;
    font-style: inherit;
    color: cornflowerblue;
    font-size: 0.875rem;
    text-align: center;
  }
}
</style>
